import React, { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger
} from '@/components/ui/dialog'
import { createPieceProps } from '@/apis/piece'
import { PieceProps } from '@/types/piece'
import { toast } from '@/hooks/use-toast'
import { usePieceStore } from '@/store/piece'

interface CreatePropsProps {
  onSuccess?: () => void
}

export default function CreateProps({ onSuccess }: CreatePropsProps) {
  const [open, setOpen] = useState(false)
  const [formData, setFormData] = useState<Omit<PieceProps, 'id'>>({
    name: '',
    title: '',
    levels: '',
    describe: '',
    status: 1
  })
  const [loading, setLoading] = useState(false)
  const [levelsError, setLevelsError] = useState<string | null>(null)
  const { addPieceProps } = usePieceStore()

  const validateLevels = (value: string): boolean => {
    if (!value) {
      setLevelsError('等级不能为空')
      return false
    }

    const parts = value.split(',')
    const lastPart = parts[parts.length - 1]

    // 检查是否以%结尾
    const hasPercent = lastPart.endsWith('%')
    const numericParts = hasPercent
      ? parts.slice(0, -1).concat(lastPart.slice(0, -1))
      : parts

    // 检查数量是否符合最少6个的要求
    if (numericParts.length < 6) {
      setLevelsError(`等级数值最少需要6个值，当前为${numericParts.length}个`)
      return false
    }

    // 检查每个部分是否为有效数字
    for (const part of numericParts) {
      if (isNaN(Number(part)) || part.trim() === '') {
        setLevelsError(`"${part}" 不是有效的数值`)
        return false
      }
    }

    setLevelsError(null)
    return true
  }

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    const { name, value } = e.target

    // 特殊处理levels字段的验证
    if (name === 'levels') {
      validateLevels(value)
    }

    setFormData((prev) => ({
      ...prev,
      [name]: value
    }))
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    // 验证levels字段
    if (!validateLevels(formData.levels)) {
      toast({
        title: '输入错误',
        description: '请检查等级字段的输入格式',
        variant: 'destructive'
      })
      return
    }

    setLoading(true)

    try {
      // 处理levels数据，如果不足11个则用最后一个值填充
      let processedLevels = formData.levels
      const parts = formData.levels.split(',')
      const lastPart = parts[parts.length - 1]
      const hasPercent = lastPart.endsWith('%')
      const numericParts = hasPercent
        ? parts.slice(0, -1).concat(lastPart.slice(0, -1))
        : parts

      // 如果数值不足11个，用最后一个值填充到11个
      if (numericParts.length < 11) {
        const lastValue = numericParts[numericParts.length - 1]
        const filledParts = [...numericParts]
        while (filledParts.length < 11) {
          filledParts.push(lastValue)
        }

        // 重新构建levels字符串
        processedLevels = hasPercent
          ? filledParts.join(',') + '%'
          : filledParts.join(',')
      }

      const dataToSubmit: Omit<PieceProps, 'id' | 'created_at' | 'updated_at'> =
        {
          ...formData,
          levels: processedLevels
        }

      const result = await createPieceProps(dataToSubmit as PieceProps)

      if (result) {
        toast({
          title: '成功',
          description: '属性创建成功'
        })
        // 添加到store中
        addPieceProps(result)
        setOpen(false)
        setFormData({
          name: '',
          title: '',
          levels: '',
          describe: '',
          status: 1
        })
        setLevelsError(null)
        onSuccess?.()
      } else {
        toast({
          title: '错误',
          description: '创建属性失败',
          variant: 'destructive'
        })
      }
    } catch (error) {
      toast({
        title: '错误',
        description: '创建属性时发生错误: ' + (error as Error).message,
        variant: 'destructive'
      })
    } finally {
      setLoading(false)
    }
  }

  // 解析levels值用于显示示例
  const parseLevels = () => {
    if (!formData.levels) return null

    const parts = formData.levels.split(',')
    const lastPart = parts[parts.length - 1]
    const hasPercent = lastPart.endsWith('%')
    const numericParts = hasPercent
      ? parts.slice(0, -1).concat(lastPart.slice(0, -1))
      : parts

    // 如果数值不足11个，用最后一个值填充到11个
    const displayParts = [...numericParts]
    if (displayParts.length < 11) {
      const lastValue = displayParts[displayParts.length - 1]
      while (displayParts.length < 11) {
        displayParts.push(lastValue)
      }
    }

    return {
      values: displayParts,
      isPercent: hasPercent
    }
  }

  const levelsData = parseLevels()

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button
          variant="ghost"
          size="sm"
          className="h-6 rounded border-none px-1 text-[10px] text-gray-800 shadow-none hover:text-gray-900"
        >
          创建属性
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>创建新属性</DialogTitle>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label htmlFor="name" className="mb-1 block text-sm font-medium">
              名称
            </label>
            <Input
              id="name"
              name="name"
              value={formData.name}
              onChange={handleChange}
              placeholder="例如: (龟裂+炫彩)"
              required
            />
          </div>

          <div>
            <label htmlFor="title" className="mb-1 block text-sm font-medium">
              标题
            </label>
            <Input
              id="title"
              name="title"
              value={formData.title}
              onChange={handleChange}
              placeholder="例如: 龟裂+炫彩"
              required
            />
          </div>

          <div>
            <label htmlFor="levels" className="mb-1 block text-sm font-medium">
              等级
              <span className="ml-2 text-xs text-gray-500">
                (100p之间的数据效果，用逗号分隔，可选百分比符号结尾)
              </span>
            </label>
            <Input
              id="levels"
              name="levels"
              value={formData.levels}
              onChange={handleChange}
              placeholder="例如: 1,2,4,6,8,10 或 1,2,4,6,8,10%"
              required
            />
            {levelsError && (
              <p className="mt-1 text-sm text-red-500">{levelsError}</p>
            )}
            <div className="mt-2 text-xs text-gray-500">
              <p className="mb-1 font-medium">格式说明:</p>
              <ul className="list-disc space-y-1 pl-5">
                <li>输入1p-100p之间的数据效果</li>
                <li>最后一个数值可以是百分比符号 (%)</li>
                <li>最少输入6个数值，不足11个时系统会自动用最后一个值填充</li>
                <li>
                  前11个数值分别对应等级区间: 1-9p, 10-19p, 20-29p, ...,
                  100-109p
                </li>
              </ul>

              <p className="mb-1 mt-2 font-medium">示例:</p>
              <ul className="list-disc space-y-1 pl-5">
                <li>&quot;1,2,4,6,8,10&quot;: 最少6个值，不足的会用10填充</li>
                <li>
                  &quot;1,2,4,6,8,10,10,10,10,10,10%&quot;:
                  最后一个%表示所有数值都是百分比
                </li>
              </ul>

              <p className="mb-1 mt-2 font-medium">详细说明:</p>
              <ul className="list-disc space-y-1 pl-5">
                <li>
                  1 (1-9p):{' '}
                  {levelsData
                    ? `${levelsData.values[0]}${
                        levelsData.isPercent ? '%' : ''
                      }`
                    : '效果'}
                </li>
                <li>
                  2 (10-19p):{' '}
                  {levelsData
                    ? `${levelsData.values[1]}${
                        levelsData.isPercent ? '%' : ''
                      }`
                    : '效果'}
                </li>
                <li>
                  3 (20-29p):{' '}
                  {levelsData
                    ? `${levelsData.values[2]}${
                        levelsData.isPercent ? '%' : ''
                      }`
                    : '效果'}
                </li>
                <li>
                  4 (30-39p):{' '}
                  {levelsData
                    ? `${levelsData.values[3]}${
                        levelsData.isPercent ? '%' : ''
                      }`
                    : '效果'}
                </li>
                <li>
                  5 (40-49p):{' '}
                  {levelsData
                    ? `${levelsData.values[4]}${
                        levelsData.isPercent ? '%' : ''
                      }`
                    : '效果'}
                </li>
                <li>
                  6 (50-59p):{' '}
                  {levelsData
                    ? `${levelsData.values[5]}${
                        levelsData.isPercent ? '%' : ''
                      }`
                    : '效果'}
                </li>
                <li>
                  7 (60-69p):{' '}
                  {levelsData
                    ? `${levelsData.values[6]}${
                        levelsData.isPercent ? '%' : ''
                      }`
                    : '效果'}
                </li>
                <li>
                  8 (70-79p):{' '}
                  {levelsData
                    ? `${levelsData.values[7]}${
                        levelsData.isPercent ? '%' : ''
                      }`
                    : '效果'}
                </li>
                <li>
                  9 (80-89p):{' '}
                  {levelsData
                    ? `${levelsData.values[8]}${
                        levelsData.isPercent ? '%' : ''
                      }`
                    : '效果'}
                </li>
                <li>
                  10 (90-99p):{' '}
                  {levelsData
                    ? `${levelsData.values[9]}${
                        levelsData.isPercent ? '%' : ''
                      }`
                    : '效果'}
                </li>
                <li>
                  11 (100+):{' '}
                  {levelsData
                    ? `${levelsData.values[10]}${
                        levelsData.isPercent ? '%' : ''
                      }`
                    : '效果'}
                </li>
              </ul>
            </div>
          </div>

          <div>
            <label
              htmlFor="describe"
              className="mb-1 block text-sm font-medium"
            >
              描述
            </label>
            <Textarea
              id="describe"
              name="describe"
              value={formData.describe}
              onChange={handleChange}
              rows={3}
            />
          </div>

          <div className="flex justify-end space-x-2">
            <Button
              type="button"
              variant="outline"
              onClick={() => setOpen(false)}
            >
              取消
            </Button>
            <Button type="submit" disabled={loading}>
              {loading ? '创建中...' : '创建'}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  )
}
